package top.lyc829.zzl_android.logic.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.Message;

import androidx.lifecycle.MutableLiveData;

import java.io.IOException;

import okhttp3.Response;
import top.lyc829.zzl_android.logic.bean.MsgNumberBean;
import top.lyc829.zzl_android.logic.bean.ResultBean;
import top.lyc829.zzl_android.logic.network.Network;
import top.lyc829.zzl_android.logic.util.HttpUtil;
import top.lyc829.zzl_android.logic.util.Utils;
import top.lyc829.zzl_android.logic.util.gson.JsonUtilNew;

public class MsgNumberService extends Service {

    MutableLiveData<MsgNumberBean> msgNumberLiveData = new MutableLiveData<>();



    public MsgNumberService() {

    }

    @Override
    public IBinder onBind(Intent intent) {

        try {
            Network.getMsgNumber(new HttpUtil.MyCallback() {
                @Override
                public void success(Response res) throws IOException {

                    if (!res.isSuccessful()) {
                        failed(new IOException(res.message()));
                        return;
                    }

                    String resStr = res.body().string();
                    ResultBean<MsgNumberBean> resultBean = JsonUtilNew.fromJsonObject(resStr, MsgNumberBean.class);

                    if (resultBean.getCode().equals(200)) {
                        msgNumberLiveData.postValue(resultBean.getData());
                    } else {
                        failed(new IOException(resultBean.getMsg()));
                    }
                }

                @Override
                public void failed(IOException e) {
                    Utils.Sout(e.getMessage());
                    MsgNumberBean msgNumberBean = new MsgNumberBean();
                    msgNumberBean.setApplyMsgNum(0);
                    msgNumberBean.setCommentMsgNum(0);
                    msgNumberBean.setFollowMsgNum(0);
                    msgNumberBean.setPraiseMsgNum(0);
                    msgNumberBean.setSystemMsgNum(0);
                    msgNumberBean.setTotalNum(0);
                    msgNumberLiveData.postValue(msgNumberBean);
                }
            });
        } catch (Exception e) {
            Utils.Sout("getMsgNumber:" + e.getMessage());
        }



        return new MyBinder();
    }

    public MutableLiveData<MsgNumberBean> getMsgNumberLiveData() {
        return msgNumberLiveData;
    }

    public class MyBinder extends Binder {
        private MsgNumberService service = MsgNumberService.this;

        public MsgNumberService getService() {
            return service;
        }

        public void setService(MsgNumberService service) {
            this.service = service;
        }
    }

}